<template>
  <div class="app-container">
    <div class="flex box">
      <div class="flex-l">
        <!-- <div class="titles">
          <img class="titles-left-img" src="@/assets/img/yunji-1.png" alt="">
        </div> -->
        <!-- <div class="tips">安卓云机挂Q,稳定 安全 高效</div> -->
        <el-button type="primary" size="small" @click="openRentDialog" class="zdy-btn zdy-btn-rent">立即租用
          <img class="lines-img" src="@/assets/img/yunji-jiant.png" alt="">
        </el-button>
      </div>
      <!-- <div>
        <img class="titles-right-img" src="@/assets/img/yunji-2.png" alt="">
      </div> -->
    </div>
    <div class="zdy-main customTab customTabNew">
      <div class="tabs flex alc">

        <el-radio-group v-model="startType" @change="startChange">
          <el-radio-button :label="0">云机控制</el-radio-button>
          <el-radio-button :label="1">云机列表</el-radio-button>
          <el-radio-button :label="2">账号列表</el-radio-button>
          <el-radio-button :label="3">操作记录</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <div v-show="startType == 0">
      <keep-alive>
        <yunjiControl ref="yunjiControlRef" @openRentDialog="openRentDialog"></yunjiControl>
      </keep-alive>

    </div>
    <div v-if="startType == 1">
      <div class="table_box table_box_new" v-loading="loading">
        <el-table border :data="tableData.records" style="width: 100%">
          <el-table-column prop="tenantName" label="店铺名称" v-hasPermi="['searchTenantID']">

          </el-table-column>
          <el-table-column prop="id" label="云控序号">
            <template slot-scope="scope">
              云控--{{ scope.row.id }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="accountCount" label="挂Q数量">
            <template slot-scope="scope">
              <span style="color: #f60;">{{ scope.row.accountCount }}</span> /100
            </template>
          </el-table-column> -->
          <el-table-column prop="onlineStatus" label="状态">
            <template slot-scope="scope">
              <el-tag v-if="isExpiringSoon(scope.row.leaseEndTime)" type="danger" size="mini" style="margin-left: 6px;">
                即将到期
              </el-tag>
              <el-tag type="success" v-else>正常</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="leaseStartTime" label="开始时间">
            <template slot-scope="scope">
              {{ parseTime(scope.row.leaseStartTime, '{y}-{m}-{d}') }}
            </template>
          </el-table-column>
          <el-table-column prop="leaseEndTime" label="到期时间" sortable>
            <template slot-scope="scope">
              {{ parseTime(scope.row.leaseEndTime, '{y}-{m}-{d}') }}
            </template>
          </el-table-column>
          <el-table-column prop="renewal" label="自动续费">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.renewal" :active-value="2" :inactive-value="1" active-color="#6C5DD3"
                inactive-color="#999" @change="handleAutoChange(scope.row)" size="mini"></el-switch>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="renewal" label="是否远程">
            <template slot-scope="scope">
              <span v-if="scope.row.runStatus == 2">是</span>
              <span v-else>否</span>
            </template>
          </el-table-column> -->
          <el-table-column label="操作" width="160">
            <template slot-scope="scope">
              <div class="flex" style="    justify-content: center;">
                <div v-if="scope.row.isExpired == 1">
                  <!-- <el-button type="text" @click="openAddQDialog(scope.row)">添加Q</el-button> -->
                  <!-- <el-button type="text" @click="openQ(scope.row)">挂Q明细</el-button> -->
                  <el-button type="text" @click="openRenewDialog(scope.row)">续费</el-button>
                </div>
                <div v-else>
                  <el-button type="danger">已到期</el-button>
                  <!-- <el-button type="text" >删除</el-button> -->
                </div>

                <!-- <el-dropdown trigger="click" @command="(command) => handleCommand(command, scope.row)">
                  <span class="el-dropdown-link" style="font-size: 14px;">
                    更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="clear">清空所有账号</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown> -->
              </div>
            </template>
          </el-table-column>
        </el-table>

      </div>
      <div class="pages-box">
        <pagination v-show="tableData.total > 0" :total="tableData.total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />

      </div>
    </div>
    <div v-show="startType == 2">
      <div class="search-box">
        <el-form :model="formData" ref="formDataForm" :inline="true" class="search-form-new" label-width="68px">
          <el-form-item label="店铺" prop="status" v-if="checkPermi(['searchTenantID'])">
            <el-select v-model="formData.tenantId" placeholder="请选择店铺" clearable filterable>
              <el-option v-for="dict in tenantList" :key="dict.tenantId" :label="dict.tenantName"
                :value="dict.tenantId" />
            </el-select>
          </el-form-item>

          <el-form-item label="QQ账号" prop="account">
            <el-input v-model="formData.account" placeholder="请输入QQ账号" clearable size="small" />
          </el-form-item>

            <el-form-item label="容器名" prop="containerName" v-if="checkPermi(['searchTenantID'])">
            <el-input v-model="formData.containerName" placeholder="请输入容器名称" clearable size="small" />
          </el-form-item>

          <el-form-item label="状态" prop="onlineStatus" label-width="48px">
            <el-select v-model="formData.onlineStatus" placeholder="请选择状态" clearable size="small">
              <el-option label="在线" value="2" />
              <el-option label="离线" value="1" />
              <el-option label="异常" value="3" />
               <el-option label="风险" value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="出租状态" prop="rentStatus" label-width="68px" v-if="checkPermi(['yunji:qrLink'])">
            <el-select v-model="formData.rentStatus" placeholder="请选择状态" clearable size="small">
              <el-option label="出租中" value="1" />
              <el-option label="未出租" value="2" />
             
            </el-select>
          </el-form-item>
          <el-form-item label="登录时间" prop="loginTime">
            <el-date-picker v-model="loginTime" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" size="small" style="width: 300px" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
          </el-form-item>
          <el-form-item label="是否删除" prop="delFlag" v-if="checkPermi(['searchTenantID'])">
            <el-select v-model="formData.delFlag" placeholder="请选择" clearable filterable>
              <el-option label="是" value="1" />
              <el-option label="否" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="云端状态" prop="cloudStatus" v-if="checkPermi(['searchTenantID'])">
            <el-select v-model="formData.cloudStatus" placeholder="请选择云端状态" clearable filterable>
              <el-option label="存在" value="1" />
              <el-option label="删除" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleSearch">
              搜索
            </el-button>
            <el-button type="warning" icon="el-icon-refresh" size="small" @click="handleReset">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- QQ账号列表 -->
      <div class="table_box table_box_new table-section">
        <el-table border :data="qqTable.records" @sort-change="sortFun"  v-loading="loading" style="width: 100%">
          <el-table-column v-if="checkPermi(['searchTenantID'])" prop="tenantId" label="店铺id">
          </el-table-column>
          <el-table-column prop="containerName" label="云机名称" v-if="checkPermi(['searchTenantID'])"></el-table-column>
          <el-table-column v-if="checkPermi(['searchTenantID'])" prop="tenantName" label="店铺名称">
          </el-table-column>
           <el-table-column v-if="checkPermi(['searchTenantID'])" prop="containerName" label="容器名">
          </el-table-column>
          <el-table-column prop="account" label="QQ账号">
          </el-table-column>
          <el-table-column prop="createdTime" label="添加时间" width="160">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.createdTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="createdTime" label="添加时长">
            <template slot-scope="scope">
              <span class="duration-text">{{ getDay(scope.row.createdTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="loginTime" label="登录时间" width="160">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.loginTime) }}
            </template>
          </el-table-column>

          <el-table-column prop="loginTime" label="登录时长">
            <template slot-scope="scope">
              <span class="duration-text">{{ getDay(scope.row.loginTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="loginType" label="登录类型">
            <template slot-scope="scope">
              {{ scope.row.loginType === 2 ? 'QQ' : 'TIM' }}
            </template>
          </el-table-column>
          <el-table-column prop="machineType" label="登录设备">
            <template slot-scope="scope">
              {{ scope.row.machineType === 2 ? '平板' : '手机' }}
            </template>
          </el-table-column>
          <el-table-column prop="onlineStatus" label="状态" align="center">
            <template slot-scope="scope">
                  <el-tag  v-if="scope.row.onlineStatus == 2">登录</el-tag>
             <el-tag type="success" v-if="scope.row.onlineStatus == 1">未登录</el-tag>
              <el-tag type="danger" v-if="scope.row.onlineStatus == 3">异常</el-tag>
            <el-tag type="warning" v-if="scope.row.onlineStatus == 4">风险</el-tag>

            </template>
          </el-table-column>

           <el-table-column prop="rentStatus" label="出租状态" align="center" v-if="checkPermi(['yunji:qrLink'])">
            <template slot-scope="scope">
              <el-tag  :type="scope.row.rentStatus === 1 ? 'success' : 'warning'"
                size="small">
                {{ scope.row.rentStatus === 1 ? '出租中' : '未出租' }}
              </el-tag>
              <!-- <el-tag v-else type="danger" size="small">异常</el-tag> -->
            </template>
          </el-table-column>
          <el-table-column prop="offlineTime" label="异常时间" width="160" sortable>
            <template slot-scope="scope">
              <span class="danger-text">{{ scope.row.offlineTime }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="checkPermi(['searchTenantID'])" prop="delFlag" label="是否删除" align="center">
            <template slot-scope="scope">
              {{ scope.row.delFlag === 2 ? '否' : '是' }}
            </template>
          </el-table-column>
          <el-table-column v-if="checkPermi(['searchTenantID'])" prop="cloudStatus" label="云端状态" align="center">
            <template slot-scope="scope">
              {{ scope.row.cloudStatus === 2 ? '删除' : '存在' }}
            </template>
          </el-table-column>
             <el-table-column  prop="remark" label="备注" align="center">
          
          </el-table-column>
          <el-table-column label="操作" width="240" align="center">
            <template slot-scope="scope">
                <el-button type="text" class="warning-text"  @click="handleEditRemark(scope.row)">
                修改备注
              </el-button>

              <el-button type="text" :disabled="scope.row.status === 1" @click="handleOpenAccount(scope.row)">
                打开账号
              </el-button>
              <!-- <el-button type="text" :disabled="scope.row.onlineStatus != 2" @click="openYunji(scope.row)">
                自动上号
              </el-button> -->
              <!-- <el-button
              type="text"

               class="warning-text"
              :disabled="scope.row.status === 1"
              @click="handleCloseAccount(scope.row)"
            >
              关闭账号
            </el-button> -->
              <el-button type="text" class="danger-text" @click="handleDeleteAccount(scope.row)">
                删除
              </el-button>
              <!-- <el-button type="text" class="warning-text" @click="showStatus(scope.row)">
                刷新状态
              </el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="pagination-section">
        <pagination v-show="qqTable.total > 0" :total="qqTable.total" :page.sync="formData.pageNum"
          :limit.sync="formData.pageSize" @pagination="getQQList" />
      </div>
    </div>

    <div v-if="startType == 3">
      <div class="search-box">
        <el-form :model="caozuojiluForm" ref="caozuojiluFormRef" :inline="true" class="search-form-new"
          label-width="68px">
          <el-form-item label="店铺" prop="tenantId" v-if="checkPermi(['searchTenantID'])">
            <el-select v-model="caozuojiluForm.tenantId" placeholder="请选择店铺" clearable filterable>
              <el-option v-for="dict in tenantList" :key="dict.tenantId" :label="dict.tenantName"
                :value="dict.tenantId" />
            </el-select>
          </el-form-item>
          <el-form-item label="操作人" prop="operateUserId">
            <el-select filterable clearable v-model="caozuojiluForm.operateUserId" placeholder="请选择操作人">
              <el-option v-for="(item, key) in yuangongList" :key="key" :label="item.nickName" :value="item.userId" />
            </el-select>
          </el-form-item>
          <el-form-item label="操作类型" prop="operateType" label-width="68px">
           <el-select 
  v-model="caozuojiluForm.operateType" 
  placeholder="请选择操作类型" 
  clearable 
  size="small"
>
  <el-option label="创建账号" value="创建账号" />
  <el-option label="登录失败" value="登录失败" />
  <el-option label="确认登录" value="确认登录" />
  <el-option label="删除账号" value="删除账号" />
  <el-option label="打开账号" value="打开账号" />
  <el-option label="关闭账号" value="关闭账号" />
  <el-option label="自动上号" value="自动上号" />
  <el-option label="手动上号" value="手动上号" />
  <el-option label="秘钥上号" value="秘钥上号" />
</el-select>
          </el-form-item>
          <el-form-item label="操作账号" prop="operateAccount">
            <el-input v-model="caozuojiluForm.operateAccount" placeholder="请输入QQ账号" clearable size="small" />
          </el-form-item>
          <el-form-item label="操作状态" prop="operateState">
            <el-select v-model="caozuojiluForm.operateState" placeholder="请选择云端状态" clearable filterable>
              <el-option label="成功" value="1" />
              <el-option label="失败" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="操作时间" prop="caozuoLogin">
            <el-date-picker v-model="caozuoLogin" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" size="small" style="width: 300px" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="getOperateList">
              搜索
            </el-button>
            <el-button type="warning" icon="el-icon-refresh" size="small" @click="resert">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- <el-button style="margin-bottom: 10px;" type="primary" icon="el-icon-refresh" size="small" @click="getOperateList()">
              刷新
            </el-button> -->

      <!-- 操作记录 -->
      <div class="table_box table_box_new table-section">
        <el-table border :data="caozuojilu.records" v-loading="loading" style="width: 100%">

          <el-table-column v-if="checkPermi(['searchTenantID'])" prop="tenantId" label="店铺ID">
          </el-table-column>
          <el-table-column v-if="checkPermi(['searchTenantID'])" prop="tenantName" label="店铺名称" width="160">
          </el-table-column>
          <el-table-column prop="operateUserName" label=" 操作人名称">
          </el-table-column>
          <el-table-column prop="operateType" label="操作类型" width="160">
          </el-table-column>
          <el-table-column prop="operateAccount" label="操作账号">
          </el-table-column>
          <el-table-column prop="operateState" label="操作状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.operateState == 1" type="success" size="small">
                成功
              </el-tag>
              <el-tag v-else type="danger" size="small">
                失败
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column v-if="checkPermi(['searchTenantID'])" prop="operateRes" label="操作返回">
            <template slot-scope="scope">
              <el-popover placement="right" width="500" trigger="click">
                <div>{{ scope.row.operateRes }}</div>
                <span slot="reference">查看</span>
              </el-popover>
            </template>

          </el-table-column>
          <el-table-column prop="createTime" label="操作时间" width="160">
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-section">
        <pagination v-show="caozuojilu.total > 0" :total="caozuojilu.total" :page.sync="caozuojiluForm.pageNum"
          :limit.sync="caozuojiluForm.pageSize" @pagination="getOperateList" />
      </div>
    </div>
    <!-- 云机租用/续费弹窗 -->
    <CloudMachineDialog :visible.sync="dialogVisible" :type="dialogType" :machine-data="selectedMachine" :yudou="yudou"
      @success="handleDialogSuccess" @close="handleDialogClose" />

    <!-- 挂Q明细弹窗 -->
    <!-- <QDetailDialog :visible.sync="qDetailVisible" :selectedQ="selectedQ" @close="handleQDetailClose"
      @deleteSuccess="getList" @update="qUpdate" @add="addQdualog" /> -->

    <!-- 添加挂Q弹窗 -->
    <!-- <AddQDialog :visible.sync="addQVisible" :selectedQ="selectedQ" @success="handleAddQSuccess"
      @close="handleAddQClose" /> -->

    <!-- 云机弹窗 -->
    <!-- <yunjiWeburl ref="yunjiWeburlRef" @update="yunjiUpdate" @@close="handleLinkClose"></yunjiWeburl> -->

    <!--    上传图片弹窗-->
    <el-dialog title="自动上号" :visible.sync="uploadDialog" class="login-dialog" center :auto-upload="false" width="40%">
      <div :class="{ 'paste-focus': pasteFocus }" class="paste-container" contenteditable="true"
        @blur="pasteFocus = false" @focus="pasteFocus = true" @paste="handlePasteImage">
        <p>在使用微信截图或复制图片后，</p>
        <p>可点击此区域粘贴图片（
          <el-tag style="font-weight: bold;" type="success">Ctrl</el-tag>
          +
          <el-tag style="font-weight: bold;">V</el-tag>
          或
          <el-tag style="font-weight: bold;" type="success">右键</el-tag>
          选择
          <el-tag style="font-weight: bold;">粘贴</el-tag>
          ）
        </p>
      </div>
      <el-upload accept="image/png,image/jpeg,image/jpg" drag class="login-uploader" action="" :show-file-list="false"
        :before-upload="beforeAvatarUpload">
        <div v-if="loginQrCode.imageUrl" class="image-viewer">
          <img alt="" :src="loginQrCode.imageUrl" class="image-viewer_image">
        </div>
        <div v-else>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过2MB</div>
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleScanLogin">确 定</el-button>
      </span>
    </el-dialog>

    <!--账号列表  修改备注 -->
    <el-dialog title="修改备注" :visible.sync="editRemarkDialog" class="login-dialog" center width="30%">
      <el-form ref="editRemarkForm" :model="editRemarkForm" label-width="80px">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editRemarkForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
       <span slot="footer" class="dialog-footer">
        <el-button @click="editRemarkDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleEditRemarkSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>
<script>

import {
  delAccount,
  delAllAccount,
  renewal,
  getAllList,
  linkClose,
  openAccount,
  scanAuto,
  seeStatus,
  tenantLists,
  operateList,
  yunjiRemark
} from '@/api/tenantApis/cloudMachine'
import yunjiControl from './components/yunjiControl.vue'
import CloudMachineDialog from './components/CloudMachineDialog.vue'
// import QDetailDialog from './components/QDetailDialog.vue'
// import AddQDialog from './components/AddQDialog.vue'
// import yunjiWeburl from './components/yunjiWeburl.vue'
import { getDicts } from "@/api/system/dict/data";

import { convertImageToPNG } from '../../../utils/makeImgs-utils/getUrlImg'
import supplyConfigApi from "@/api/system/supplyConfig";


export default {
  name: "CloudMachine",
  components: {
    CloudMachineDialog,
    // QDetailDialog,
    // AddQDialog,
    // yunjiWeburl,
    yunjiControl,
  },
  computed: {
    tenantList() {
      return this.$store.getters.tenantList;
    },
  },
  data() {
    return {
      loginQrCode: {
        imageUrl: '',
        fileSource: null
      },
      pasteFocus: false,
      uploadDialog: false,
      startType: '0',
      bstateMap: [
        { label: '离线', value: 1 },
        { label: '在线', value: 2 }
      ],
      queryParams: {
        pageSize: 10,
        pageNum: 1
      },
      loading: false,
      tableData: {
        records: [],
        total: 0
      },
      // 弹窗相关
      dialogVisible: false,
      dialogType: 'add', // 'add' 或 'renew'
      selectedMachine: {},
      // 挂Q明细弹窗
      qDetailVisible: false,
      selectedQ: {},
      // 添加挂Q弹窗
      addQVisible: false,
      yudou: '',
      isYunji: false,

      //qq列表
      formData: {

        pageNum: 1,
        pageSize: 10,
        account: '',

        status: '',
      },
      loginTime: [],
      qqTable: {
        records: [],
        total: 0
      },

      accountId: '',
      loadingInstance: null,

      caozuojilu: {
        records: [],
        total: 0
      },
      caozuojiluForm: {
        pageNum: 1,
        pageSize: 10,
        tenantId: '',

        operateUserId: '',
        operateType:'',
        operateAccount: '',
        operateState: '',
        beginCreateTime: '',
        endCreateTime: ''
      },
      caozuoLogin: [],
      yuangongList: [],

      editRemarkDialog:false,
      editRemarkForm:{
        id:'',
        remark:''
      }
    }
  },
  created() {
    // this.getList()
    this.getMachine()
  },
  mounted() {
  },
  destroyed() {
  },
  methods: {
    sortFun(val) {
      console.log(val)
      if(val&&val.order=='descending') {
        this.formData.offTimeSort = 'desc';
      }else {
        this.formData.offTimeSort = 'asc';
      }
      this.getQQList()
    },
    async handleScanLogin() {
      if (!this.loginQrCode.fileSource) {
        this.$modal.msgError('请先选择图片')
        return
      }
      this.uploadDialog = false
      const loginLoading = this.$loading({
        lock: true,
        text: '自动上号中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
        customClass: 'highlight-loading', // 自定义类名，用于添加样式
      });

      const pngFile = await convertImageToPNG(this.loginQrCode.fileSource);
      const form = new FormData();
      form.append('file', pngFile);
      form.append('accountId', this.accountId);
      form.append('isCheck', 1);
      scanAuto(form).then(res => {
        if (res.code == 200) this.$modal.msgSuccess(`${this.accountId}上号成功`)
        else this.$modal.msgError(`${this.accountId}上号失败`)
      }).catch(err => this.$modal.msgError(err)).finally(() => loginLoading.close())

    },
    handlePasteImage(event) {
      // 阻止默认粘贴行为（避免粘贴文本到页面）
      event.preventDefault();
      const clipboardData = event.clipboardData || window.clipboardData;

      const items = clipboardData.items;
      for (let i = 0; i < items.length; i++) {
        const item = items[i];
        // 判断是否为图片类型
        if (item.type.indexOf('image') !== -1) {
          // 获取图片文件对象
          const file = item.getAsFile();
          if (file) {
            // 将文件转为可预览的 URL（使用 URL.createObjectURL）
            this.loginQrCode.imageUrl = URL.createObjectURL(file);
            // 这里可以添加上传图片的逻辑（例如调用接口上传 file 对象）
            console.log('获取到剪贴板图片：', file);
            this.loginQrCode.fileSource = file
            break;
          }
        }
      }
      if (this.loginQrCode.fileSource == null) this.$modal.msgError('请粘贴图片！')

    },
    beforeAvatarUpload(file) {
      const isJPG = file.type.indexOf('image');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (isJPG == -1) {
        this.$message.error('上传文件类型需要为图片');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      this.loginQrCode.imageUrl = URL.createObjectURL(file);
      this.loginQrCode.fileSource = file
      return false;
    },
    startChange(e) {
      if (e == 1) {
        this.queryParams.pageNum = 1;  // 重置页码
        this.tableData = {
          records: [],
          total: 0
        };
        this.getList()
      } else if (e == 2) {
        this.loginTime = []
        // this.formData.pageNum = 1;  // 重置页码
        //  this.formData.pageSize = 10
        // this.qqTable = {
        //   records: [],
        //   total: 0
        // };
        this.getQQList()
      } else if (e == 3) {
        this.caozuojiluForm.pageNum = 1;  // 重置页码
        this.caozuojiluForm.pageSize = 10
        this.caozuojilu = {
          records: [],
          total: 0
        };
        this.getYuangongList()
        this.getOperateList()

      }
    },
    getYuangongList() {
      supplyConfigApi.getAllUserList({
        userNewType: 1,
      })
        .then((res) => {
          this.yuangongList = res.rows;
        });
    },
    resert() {
      this.$refs.caozuojiluFormRef.resetFields()
      this.caozuoLogin = []
      this.caozuojiluForm= {
        pageNum: 1,
        pageSize: 10,
        beginCreateTime: '',
        endCreateTime: ''
      }
      this.getOperateList()
    },
    getOperateList() {
      if(this.caozuoLogin.length>0) {
        this.caozuojiluForm.beginCreateTime = this.caozuoLogin[0]
        this.caozuojiluForm.endCreateTime = this.caozuoLogin[1] + ' ' + '23:59:59'
      }
      operateList(this.caozuojiluForm).then(res => {
        this.caozuojilu.records = res.rows
        this.caozuojilu.total = res.total
      })
    },
    // 监听云机弹窗关闭, 关闭云机连接
    // handleLinkClose(row) {
    //   linkClose(row)
    // },
    yunjiUpdate(data) {
      this.selectedQ = data
      this.qDetailVisible = true
    },

    qUpdate(data, wss_url, sessionId) {
      this.$refs.yunjiWeburlRef.open(data, wss_url, sessionId, false, 2)
    },
    handleCommand(command, row) {
      switch (command) {
        case "clear":
          this.allClear(row);
          break;

        default:
          break;
      }
    },
    async allClear(val) {

      await this.$confirm(`此操作将删除全部账号, 是否继续？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await delAllAccount(val.machineId)
      this.$message.success('删除成功！')
      this.getList()
    },
    getMachine() {
      {
        getDicts('machine').then(res => {
          const foundItem = res.data.find(item => item.dictLabel === 'amount');
          if (foundItem) {
            this.yudou = foundItem.dictValue;
          }
        })
      }
    },
    getList() {
      this.loading = true;
      tenantLists(this.queryParams).then(res => {
        this.tableData.records = res.rows;
        this.tableData.total = res.total;
      }).finally(() => {
        this.loading = false;
      });
    },
    search() {
      this.getList()
    },

    // 打开租用弹窗
    openRentDialog() {
      this.dialogType = 'add'
      this.selectedMachine = {}
      this.dialogVisible = true
    },

    // 打开续费弹窗
    openRenewDialog(row) {
      this.dialogType = 'renew'
      this.selectedMachine = {
        machineId: row.machineId, // 云机编号
        expireTime: row.leaseEndTime, // 到期时间
        id: row.id,
        renewal: row.renewal
      }
      this.dialogVisible = true
    },

    // 弹窗操作成功回调
    handleDialogSuccess() {
      this.getList() // 刷新列表
      this.$nextTick(() => {
        // 刷新yunjiControl组件的云机实例列表
        this.$refs.yunjiControlRef.getList('add')
      })
    },
    // 弹窗关闭回调
    handleDialogClose() {
      this.dialogVisible = false
      this.selectedMachine = {}
    },
    addQdualog(data) {
      this.selectedQ = data
      this.addQVisible = true
    },

    // 打开挂Q明细弹窗
    openQ(row) {
      this.selectedQ = row
      this.qDetailVisible = true
    },

    // 挂Q明细弹窗关闭回调
    handleQDetailClose() {
      this.qDetailVisible = false
      this.selectedMachineId = ''
    },
    // async checkMachineOccupied(machineId) {
    //   const show = await checkYunji(machineId)
    //   const runStatus = show.data?.runStatus
    //   if (runStatus == 2) {
    //     this.$modal.confirm("该云机当前已被占用,强制登录会导致远程异常,确定强制登录吗？", "温馨提示", {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     }).then(() => {
    //       return true
    //     }).catch(() => {
    //       this.$modal.msg("取消操作")
    //     })
    //   }
    //   return true // 未占用，允许继续
    // },
    // 打开添加挂Q弹窗@
    // async openAddQDialog(row) {
    //   const canProceed = await this.checkMachineOccupied(row.machineId)
    //   if (!canProceed) return
    //   // 关闭连接
    //   linkClose(row.machineId)
    //   this.selectedQ = row
    //   this.addQVisible = true
    // },
    // 添加挂Q成功回调
    // handleAddQSuccess(data, wss_url, sessionId,) {
    //   this.$refs.yunjiWeburlRef.open(data, wss_url, sessionId, true, 1)
    //   this.getList() // 刷新列表
    // },

    // 添加挂Q弹窗关闭回调
    // handleAddQClose() {
    //   console.log('添加挂Q弹窗关闭回调')
    //   this.addQVisible = false
    //   this.selectedMachineId = ''
    // },

    isExpiringSoon(dateStr) {
      if (!dateStr) return false;
      const now = new Date();
      const end = new Date(dateStr);
      // 计算剩余天数
      const diff = (end - now) / (1000 * 60 * 60 * 24);
      return diff <= 5 && diff > 0;
    },
    handleAutoChange(row) {
      const originalRenewal = row.renewal === 2 ? 1 : 2;
      let statues = row.renewal == 2 ? '开启自动续费' : '关闭自动续费'
      this.$confirm(`确定要${statues} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await renewal({ id: row.id, renewal: row.renewal })
        this.$message.success('操作成功')
        this.getList()
      }).catch(() => {
        row.renewal = originalRenewal;
      })
    },


    //qq账号

    // 搜索
    handleSearch() {
      this.formData.pageNum = 1
      this.getQQList()
    },
    getQQList() {
      this.loading = true;
      console.log(this.loginTime)
      if (this.loginTime.length == 0) {
        this.formData.startTime = ''
        this.formData.endTime = ''
      } else {
        this.formData.startTime = this.loginTime[0]
        this.formData.endTime = this.loginTime[1] + ' ' + '23:59:59'
      }
      getAllList(this.formData).then(res => {
        this.qqTable.records = res.rows
        this.qqTable.total = res.total
      }).finally(() => {
        this.loading = false;
      });
    },
    // 重置
    handleReset() {
      this.resetQueryParams()
      this.getQQList()
    },
    // 重置查询参数
    resetQueryParams() {
      this.loginTime = []
      this.formData = {
        pageNum: 1,
        pageSize: 10,
        account: '',
        status: '',
        startTime: '',
        endTime: '',
        rentStatus:''
      }
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    },
    getDay(val) {
      if (!val) {
        return '---'
      }
      const now = new Date();
      const start = new Date(val);
      if (isNaN(start.getTime())) return '0天0小时';
      // 计算时间差（毫秒）
      const timeDiff = now.getTime() - start.getTime();
      if (timeDiff <= 0) return '0天0小时';
      const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
      const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      return `${days}天${hours}小时`;
    },
    async handleOpenAccount(row) {
      try {
        this.loading = true
        let data = {
          id: row.id
        }
        const res = await openAccount(data)
        if (res.data.wssUrl) {
          let datas = {
            sessionId: res.data.sessionId,
            wss_url: res.data.wssUrl,
            accountId: res.data.accountId,
            account: res.data.account,
            id: row.id,
            loginType: row.loginType,
            machineType: row.machineType,
            onlineStatus: row.onlineStatus,
            loginTime: row.loginTime,
            createDays: row.createDays,
            createdTime: row.createdTime
          }
          this.loading = false
          this.startType = 0

          this.$nextTick(() => {
            // 调用yunjiControl组件的openUrlForInstance方法
            this.$refs.yunjiControlRef.openUrlForInstanceFromParent(datas, 'see')
          })
        }
      } catch (error) {
        this.loading = false
        if (error !== 'cancel') {
          console.error('打开账号失败:', error)
        }
      }
    },
    triggerScanUpload() {
      let that = this
      // 1. 防重复：先关闭已有 loading（避免多个 loading 残留）
      if (this.loadingInstance) {
        this.loadingInstance.close();
        this.loadingInstance = null;
      }
      try {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/png,image/jpeg,image/jpg';
        input.style.display = 'none';
        document.body.appendChild(input);


        input.addEventListener('change', async (e) => {
          // 2. 创建并显示 loading
          that.loadingInstance = that.$loading({
            lock: false, // 允许交互（或根据需求设为 true）
            text: '自动上号中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)', // 深色半透明背景，突出前景
            customClass: 'highlight-loading', // 自定义类名，用于添加样式
          });
          const file = e.target.files[0];
          const cleanUp = () => {
            this.loadingInstance.close();
            document.body.removeChild(input);
            this.loadingInstance = null;
          };

          if (!file) {
            cleanUp();
            return;
          }

          // 验证文件大小
          if (file.size > 1 * 1024 * 1024) {
            this.$message.error('图片不能超过1MB');
            cleanUp();
            return;
          }

          try {
            const pngFile = await convertImageToPNG(file);
            const form = new FormData();
            form.append('file', pngFile);
            form.append('accountId', this.accountId);
            const data = await scanAuto(form);
            if (data.code === 200) {
              this.$message.success('上号成功');
            } else {
              this.$message.error('上传或写入失败');
            }
          } catch (err) {
            // this.$message.error('处理失败：' + (err.message || '未知错误'));
          } finally {
            cleanUp(); // 无论成功失败，都清理
          }
        });

        // 5. 触发文件选择框（必须在事件绑定后执行）
        input.click();

      } catch (e) {
        // 创建 input 失败时的处理
        this.loadingInstance.close();
        this.loadingInstance = null;
        this.$message.error('打开文件选择器失败：' + e.message);
      }
    },
    async openYunji(row) {
      this.accountId = row.id
      // this.triggerScanUpload()
      this.loginQrCode = {
        imageUrl: '',
        fileSource: null
      }
      this.uploadDialog = true
    },

    // 删除账号
    async handleDeleteAccount(row) {
      try {
        await this.$confirm(`确定要删除账号 ${row.account} 吗？删除后不可恢复！`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        let data = {
          id: row.id,
        }
        // 调用删除账号的API
        await delAccount(data)
        this.$message.success('账号删除成功')
        this.getQQList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除账号失败:', error)
        }
      }
    },
    showStatus(row) {
      let data = {
        id: row.id,
      }
      seeStatus(data).then(res => {
        this.$message.success('刷新成功')
        this.getList()
      })
    },

    handleEditRemark(row) {
      this.editRemarkForm.id = row.id
      this.editRemarkForm.remark = row.remark
      this.editRemarkDialog = true
    },

    handleEditRemarkSubmit() {
        yunjiRemark(this.editRemarkForm).then(res=> {
          this.$message.success('修改成功')
           this.getQQList()

        }).finally(()=> {
          this.editRemarkDialog = false
        })
    }
  },
};

</script>
<style lang="scss" scoped>
// 自动扫码上号
.login-dialog {
  ::v-deep.el-upload-dragger {
    width: 250px;
    min-height: 250px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .paste-focus {
    background: #897ddc;
    color: #FFFFFF;
  }

  .paste-container {
    margin: 30px 0 30px;
    padding: 20px 20px;
    border-radius: 8px;
    cursor: pointer;
    width: 100%;
    height: 150px;
    border: 1px #999999 dashed;

    &:hover {
      border-color: #897ddc;
    }
  }

  .login-uploader {
    display: flex;
    justify-content: center;
    width: 100%;

    .image-viewer {
      &_image {
        width: 100%;
        object-fit: cover;
      }
    }
  }
}


.box {
  align-items: center;
  border-radius: 4px;
  // padding: 10px 60px 20px;
  // background: url('../../../assets/img/yunji-bg.png') no-repeat;
  // background-size: 100% 100%;1
  margin-bottom: 10px;

  .flex-l {
    flex: 1;
  }

  .titles {
    color: rgba(51, 51, 51, 1);
    font-size: 18px;
  }

  .tips {
    color: #030C22;
    font-size: 24px;
    text-decoration-line: underline;
    margin: 0px 0 15px;
  }
}

.titles-left-img {
  width: 170px;
  // height: 86px;
}

.titles-right-img {
  width: 200px;
}

.zdy-btn-rent {
  width: 120px;
  margin-left: 5px;
  font-size: 16px;
  height: 32px;
}

.lines-img {
  margin-top: 2px;
  vertical-align: text-top;
  width: 18px;
  margin-left: 2px;
}

.duration-text {
  color: #409eff;
  font-weight: bold;
}

.warning-text {
  color: #faad14;
  margin-left: 0;
}

.danger-text {
  color: #f56c6c;
  margin-left: 0;
}
</style>
<style lang="scss">
/* 全局加载样式强化 */


.highlight-loading {
  /* 1. 提高层级，覆盖其他内容 */
  z-index: 9999 !important;

  /* 2. 加载动画放大 + 颜色突出 */
  .el-loading-spinner {
    top: 45% !important;
    /* 居中偏上，更醒目 */
    transform: translateY(-50%) scale(1.5);
    /* 放大 1.5 倍 */

    .el-icon-loading {
      font-size: 48px !important;
      /* 图标放大 */
      color: #409eff !important;
      /* 亮蓝色，对比深色背景 */
      animation: rotate 1.5s linear infinite;
      /* 加快旋转速度 */
    }

    /* 3. 文字强化 */
    .el-loading-text {
      margin-top: 20px !important;
      font-size: 18px !important;
      color: #fff !important;
      /* 白色文字，与深色背景对比 */
      font-weight: bold;
      text-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
      /* 文字阴影，增强可读性 */
    }
  }

  /* 4. 可选：添加背景动效（呼吸渐变） */
  &::before {
    content: '';
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: radial-gradient(circle at center, rgba(64, 158, 255, 0.2) 0%, transparent 70%);
    animation: pulse 3s infinite;
  }

}

/* 自定义动画：加快旋转 */
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

/* 自定义动画：呼吸效果 */
@keyframes pulse {

  0%,
  100% {
    opacity: 0.6;
  }

  50% {
    opacity: 0.3;
  }
}

/* 可选：如果使用 content 自定义内容 */
.loading-content {
  text-align: center;

  .el-icon-camera {
    font-size: 50px;
    color: #409eff;
    margin-bottom: 15px;
    animation: bounce 2s infinite;
  }

  p {
    color: #fff;
    font-size: 18px;
    font-weight: bold;
  }
}

@keyframes bounce {

  0%,
  100% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.1);
  }
}
</style>
